<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import SecondaryCard from '@/views/home-view/secondaryCard.vue'
import * as echarts from 'echarts'
import { Message } from 'element-ui'
import {
  getHomeProposalGroupInfo,
  getHomeProposalInfo,
  getHomeSatisfactionGraphInfo,
  getHomeSatisfactionInfo,
} from '@/api/home-view'
import { group, sum } from '@/utils/radash'
import { queryTotal } from '@/api/question'
import OrderPanel from '@/components/order-panel'

defineProps({
  level: {
    type: String,
    default: '',
  },
  codeShow: {
    type: Boolean,
    default: false,
  },
})

const chartShow = ref(true)
const suggestShow = ref(true)

const user = JSON.parse(localStorage.getItem('user'))?.user || {}
chartShow.value = user.roleLevel === 0 || user.roleLevel === 4

const regionInfo = reactive({
  regionCount: '0',
  streetCount: '0',
  communityCount: '0',
  satisfactionCount: '0',
  streetJoinCount: '0',
  communityJoinCount: '0',
  regionJoinCount: '0',
  regionPercent: '',
  suggestCount: '0',
})

const value = 66
const rate = value + '%'
const rateOption = {
  backgroundColor: '#fff',
  title: {
    text: rate,
    left: '20%',
    top: '40%',
    itemGap: 8,
    textStyle: {
      color: 'black',
      fontSize: '16',
      fontWeight: 400,
    },
    // subtext: '达标率',
    // subtextStyle: {
    //   color: 'black',
    //   fontSize: '20',
    //   fontWeight: 400,
    // },
  },
  tooltip: {},
  angleAxis: {
    max: 100,
    // 隐藏刻度线
    show: false,
    startAngle: 90,
  },
  radiusAxis: {
    type: 'category',
    show: true,
    axisLabel: {
      show: false,
    },
    axisLine: {
      show: false,
    },
    axisTick: {
      show: false,
    },
  },
  polar: {
    radius: ['70%', '90%'],
    center: ['36%', '50%'],
  },
  series: [
    {
      type: 'bar',
      data: [value],
      showBackground: true,
      roundCap: true,
      backgroundStyle: {
        color: 'rgb(232,232,232)',
      },
      coordinateSystem: 'polar',
      barWidth: 12,
      itemStyle: {
        normal: {
          color: 'rgb(33, 203, 254)',
          // color: {
          //   type: 'linear',
          //   x: 0,
          //   y: 0,
          //   x2: 0,
          //   y2: 1,
          //   colorStops: [
          //     {
          //       offset: 0,
          //       color: '#43CBFF',
          //     },
          //     {
          //       offset: 1,
          //       color: '#9708CC',
          //     },
          //   ],
          //   global: false,
          // },
        },
      },
    },
  ],
}

let rateChart
const rateChartRef = ref()

const initChart = () => {
  rateChart = echarts.init(rateChartRef.value, 'light')
  rateChart.setOption(rateOption)
}

const roseOption = {
  toolbox: {
    show: false,
  },
  tooltip: {
    // trigger: 'item',
    formatter: (params) => {
      return `${params.marker}${params.name}(${params.percent}%)`
    },
  },
  legend: {
    left: 'center',
    top: '66%',
    // textStyle: {
    width: 325,
    // },
    // data: [
    //   'rose1',
    //   'rose2',
    //   'rose3',
    //   'rose4',
    //   'rose5',
    //   'rose6',
    //   'rose7',
    //   'rose8',
    // ],
  },
  series: [
    {
      // name: 'Nightingale Chart',
      type: 'pie',
      radius: [40, 80],
      center: ['50%', '33%'],
      roseType: 'radius',
      itemStyle: {
        borderRadius: 12,
      },
      label: {
        show: false,
      },
      emphasis: {
        label: {
          show: true,
        },
      },
      data: [
        { value: 40, name: 'rose 1' },
        { value: 38, name: 'rose 2' },
        { value: 32, name: 'rose 3' },
        { value: 30, name: 'rose 4' },
        { value: 28, name: 'rose 5' },
        { value: 26, name: 'rose 6' },
        { value: 22, name: 'rose 7' },
        { value: 18, name: 'rose 8' },
      ],
    },
  ],
}

let roseChart
const roseChartRef = ref()

const initRoseChart = () => {
  if (!roseChartRef.value) return
  roseChart = echarts.init(roseChartRef.value, 'light')
  roseChart.setOption(roseOption)
}

const centerOption = {
  color: ['rgb(56, 148, 255)'],
  legend: {
    top: '2%',
    left: 'center',
    itemWidth: 10,
    itemHeight: 8,
    itemGap: 15,
    textStyle: {
      fontFamily: 'MicrosoftYaHei',
      fontSize: 12,
      color: 'black',
    },
    // data: [],
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  grid: {
    left: '1%',
    top: '10%',
    right: '5%',
    bottom: '2%',
    containLabel: true,
  },
  xAxis: {
    type: 'value',
    position: 'top',
    // data: [],
    // interval: true,
    axisLine: {
      show: true,
    },
    splitLine: {
      show: true,
    },
    axisLabel: {
      show: true,
      margin: 14,
      fontFamily: 'MicrosoftYaHei',
      fontSize: 12,
      color: 'rgba(113, 113, 113, 1)',
    },
    axisTick: {
      show: false,
    },
  },
  yAxis: {
    type: 'category',
    data: [],
    nameTextStyle: {
      fontFamily: 'PingFangSC-Regular, PingFang SC',
      fontSize: 12,
      color: '#999999',
    },
    axisLine: {
      show: false,
      lineStyle: {
        color: 'rgba(52, 51, 51, 1)',
      },
    },
    splitLine: {
      show: false,
    },
    axisLabel: {
      show: true,
      margin: 10,
      fontFamily: 'MicrosoftYaHei',
      fontSize: 12,
      color: 'rgba(113, 113, 113, 1)',
      interval: 0,
      // rotate: -20, //角度顺时针计算的
    },
    axisTick: {
      show: false,
    },
  },
  series: [
    {
      name: '问卷统计',
      type: 'bar',
      stack: 'truck',
      // barWidth: 15,
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 3,
        normal: {
          label: {
            show: true,
            position: 'right',
            // color: 'rgb(67, 234, 128)',
            color: 'rgb(56, 148, 255)',
          },
          // color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //   { offset: 0, color: 'rgba(56, 248, 212, .8)' },
          //   { offset: 1, color: 'rgba(67, 234, 128, .8)' },
          // ]),
        },
      },
      label: {
        show: true,
      },
      data: [],
    },
  ],
}

const centerRightOption = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  grid: {
    left: '1%',
    top: '10%',
    right: '5%',
    bottom: '2%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      show: true,
      margin: 14,
      fontFamily: 'MicrosoftYaHei',
      fontSize: 12,
      color: 'rgba(113, 113, 113, 1)',

      interval: 0,
      rotate: 50, //角度顺时针计算的
    },
  },
  yAxis: {
    name: '完成率（%）',
    type: 'value',
  },
  series: [
    {
      data: [],
      type: 'line',
      smooth: true,
    },
  ],
}

let centerChart
const centerChartRef = ref()

const initCenterChart = () => {
  if (!centerChartRef.value) return
  centerChart = echarts.init(centerChartRef.value, 'light')
  centerChart.setOption(centerOption)
}

let centerRightChart
const centerRightChartRef = ref()

const initCenterRightChart = () => {
  if (!centerRightChartRef.value) return
  centerRightChart = echarts.init(centerRightChartRef.value, 'light')
  centerRightChart.setOption(centerRightOption)
}

onMounted(() => {
  // initChart()
  initRoseChart()
  // initCenterChart()
  // initCenterRightChart()
})

const getBaseInfo = (params) => {
  getHomeSatisfactionInfo(params).then((res) => {
    if (res.success) {
      Object.assign(regionInfo, res.data)
      // const total = res.data.regionCount ? +res.data.regionCount ?? 1 : 1
      // const join = res.data.regionJoinCount ? +res.data.regionJoinCount || 0 : 0
      // regionInfo.regionRate = ((join / total) * 100).toFixed(2)
    } else {
      Message.error(res.message)
    }
  })
}

let init = false

const getRateGroupInfo = (params) => {
  if (init) {
    return
  }
  init = true
  rateGroupLoading.value = true
  getHomeProposalGroupInfo(params)
    .then((res) => {
      if (res.success) {
        const data = res.data || []
        // console.log(data)
        const obj = group(data, (f) => f.region)
        rateGroupData.value = Object.keys(obj)
          .map((name) => {
            const num = sum(obj[name], (f) => f.total ?? 0)
            return {
              name,
              num: num,
            }
          })
          .sort((a, b) => {
            return b.num - a.num
          })
      } else {
        Message.error(res.message)
      }
    })
    .finally(() => {
      rateGroupLoading.value = false
    })
}

const getChartInfo = (params) => {
  if (!roseChartRef.value) return
  if (params.communityId || params.streetId) {
    suggestShow.value = false
    return
  } else {
    suggestShow.value = true
  }
  // console.log(params.regionName)
  getHomeProposalInfo(params).then((res) => {
    if (res.success) {
      const data = res.data || []
      regionInfo.suggestCount = sum(data, (f) => f.total)
      const roseSeries = data.map((item) => {
        return {
          value: item.total,
          name: item.content + ` ${item.total}条`,
        }
      })
      // console.log(roseSeries)
      roseOption.series[0].data = roseSeries
      roseChart.setOption(roseOption)
    } else {
      Message.error(res.message)
    }
  })
}

const getCenterChartInfo = (params) => {
  if (!centerChartRef.value) return
  getHomeSatisfactionGraphInfo(params).then((res) => {
    if (res.success) {
      const list = res.data || []
      list.sort((a, b) => {
        return (a.total || 0) - (b.total || 0)
      })
      const xData =
        list
          .filter((i) => !!i.area_name && !i.area_name.includes('测试'))
          .map((i) => i.area_name) || []
      centerOption.yAxis.data = xData
      const series = centerOption.series[0]
      series.data = xData.map((x) => {
        const item = list.find((i) => i.area_name === x)
        return {
          name: x,
          value: item?.total || 0,
        }
      })
      centerChart.setOption(centerOption)
    } else {
      Message.error(res.message)
    }
  })
}

const getCenterRightChartInfo = (params) => {
  if (!centerRightChartRef.value) return
  queryTotal(params, true).then((res) => {
    if (res.success) {
      // console.log(res.data)
      const data = res.data
        .filter((i) => !!i.name && !i.name.includes('测试'))
        .map((item) => {
          const total = item.total ?? 0
          const satisfactionTotal = item.satisfactionTotal || 0
          let res = 0
          if (satisfactionTotal) {
            res = ((total / satisfactionTotal) * 100).toFixed(2)
          }
          return {
            name: item.name,
            value: res,
          }
        })
        .sort((a, b) => {
          return b.value - a.value
        })
      centerRightOption.xAxis.data = data.map((i) => i.name)
      centerRightOption.series[0].data = data.map((i) => i.value)
      centerRightChart.setOption(centerRightOption)
    } else {
      Message.error(res.message)
    }
  })
}

const totalData = ref([])
const rateData = ref([])
const totalLoading = ref(false)
const rateLoading = ref(false)
const rateGroupLoading = ref(false)
const rateGroupData = ref([])

const getTotalData = (params) => {
  if (user.roleId === 'socialmanager') {
    return
  }
  totalLoading.value = true
  getHomeSatisfactionGraphInfo(params)
    .then((res) => {
      if (res.success) {
        const list = res.data || []
        list.sort((a, b) => {
          return (b.total || 0) - (a.total || 0)
        })
        const xData =
          list
            .filter((i) => !!i.area_name && !i.area_name.includes('测试'))
            .map((i) => i.area_name) || []
        totalData.value = xData.map((x) => {
          const item = list.find((i) => i.area_name === x)
          return {
            name: x,
            num: item?.total || 0,
          }
        })
      } else {
        Message.error(res.message)
      }
    })
    .finally(() => {
      totalLoading.value = false
    })
}

let rateInit = false

const getRateData = (params) => {
  // if (!chartShow.value) {
  //   return
  // }
  // if (rateInit) {
  //   return
  // }
  if (user.roleLevel === 3) {
    return
  }
  rateLoading.value = true
  queryTotal(params, true)
    .then((res) => {
      if (res.success) {
        if (chartShow.value && !rateInit) {
          rateData.value = res.data
            .filter((i) => !!i.name && !i.name.includes('测试'))
            .map((item) => {
              const total = item.total ?? 0
              const satisfactionTotal = item.satisfactionTotal || 0
              let res = 0
              if (satisfactionTotal) {
                res = ((total / satisfactionTotal) * 100).toFixed(2)
              }
              return {
                name: item.name,
                num: res,
              }
            })
            .sort((a, b) => {
              return b.num - a.num
            })
        }
        rateInit = true
        const list = res.data || []
        list.sort((a, b) => {
          return (b.total || 0) - (a.total || 0)
        })
        const xData =
          list
            .filter((i) => !!i.name && !i.name.includes('测试'))
            .map((i) => i.name) || []
        totalData.value = xData.map((x) => {
          const item = list.find((i) => i.name === x)
          return {
            name: x,
            num: item?.total || 0,
          }
        })
      } else {
        Message.error(res.message)
      }
    })
    .finally(() => {
      rateLoading.value = false
    })
}

const inputData = (params) => {
  getBaseInfo(params)
  // getCenterChartInfo(params)
  // getCenterRightChartInfo(params)
  getChartInfo(params)
  getRateGroupInfo(params)
  // getTotalData(params)
  getRateData(params)
}

defineExpose({
  inputData,
})

const activeTab = ref('total')

const handleTabChange = (tab) => {
  if (tab) {
    const { name } = tab
    if (name === 'rate') {
      if (centerRightChartRef.value) {
        // centerRightChart.resize()
        const el = centerRightChartRef.value
        const children = el.querySelector('div')
        if (children) {
          if (children.style.width === '100%') {
            return
          }
          children.style.width = '100%'
          nextTick(() => {
            centerRightChart.resize()
          })
        }
      }
    } else {
      // if (centerChartRef.value) {
      //   centerChart.resize()
      // }
    }
  }
}

const activeSuggest = ref('type')

const handleTabChange2 = () => {}
</script>

<template>
  <div class="question-info">
    <template v-if="!codeShow">
      <div class="region-info">
        调查范围：区县共 <span>{{ regionInfo.regionCount }}</span
        >个，街道共 <span>{{ regionInfo.streetCount }}</span
        >个，社区共 <span>{{ regionInfo.communityCount }}</span
        >个
      </div>
      <div class="rate-info">
        <!--        <secondary-card title="建筑物数量" class="total-question">-->
        <!--          <div class="content-desc">-->
        <!--            <span class="num">{{ regionInfo.buildingCount }}</span-->
        <!--            ><span>栋</span>-->
        <!--          </div>-->
        <!--        </secondary-card>-->
        <secondary-card title="问卷总数" class="total-question">
          <div class="content-desc">
            <span class="num">{{ regionInfo.satisfactionCount }}</span
            ><span>份</span>
          </div>
        </secondary-card>
        <div class="center-card">
          <secondary-card title="参与街道" class="street-add">
            <div class="content-desc">
              <span class="num">{{ regionInfo.streetJoinCount }}</span
              ><span>个</span>
            </div>
          </secondary-card>
          <secondary-card title="参与社区" class="community-add">
            <div class="content-desc">
              <span class="num">{{ regionInfo.communityJoinCount }}</span
              ><span>个</span>
            </div>
          </secondary-card>
          <secondary-card
            v-show="level !== '2'"
            title="区县填报率"
            class="community-add"
          >
            <div class="content-desc">
              <span class="num">{{ regionInfo.regionPercent || '-' }}</span
              ><span>%</span>
            </div>
          </secondary-card>
        </div>

        <!--      <div class="rate-chart-content">-->
        <!--        <div class="rate-chart-title">区县填报率</div>-->
        <!--        <div class="rate-chart" ref="rateChartRef"></div>-->
        <!--      </div>-->
      </div>
      <el-tabs
        class="center-tabs"
        v-model="activeTab"
        @tab-click="handleTabChange"
      >
        <el-tab-pane
          v-if="user.roleLevel !== 3"
          label="问卷数排行"
          name="total"
        >
          <!--        <div-->
          <!--          :class="['total-chart', chartShow ? '' : 'long-chart']"-->
          <!--          ref="centerChartRef"-->
          <!--        ></div>-->
          <OrderPanel
            v-loading="rateLoading"
            :datas="totalData"
            color="#05D195"
            :hasIcon="true"
          />
        </el-tab-pane>
        <el-tab-pane v-if="chartShow" label="完成率排行" name="rate">
          <!--        <div-->
          <!--          :class="['rate-chart', chartShow ? '' : 'long-chart']"-->
          <!--          ref="centerRightChartRef"-->
          <!--        ></div>-->
          <OrderPanel
            v-loading="rateLoading"
            :datas="rateData"
            color="#05D195"
            :hasIcon="true"
          />
        </el-tab-pane>
      </el-tabs>
    </template>
    <template v-else>
      <div class="er-code">
        <img src="code.jpg" />
      </div>
      <br />
      <a class="er-link" href="https://wjpic.cstspace.cn" target="_blank"
        >重庆中心城区满意度问卷统计</a
      >
    </template>

    <div
      class="suggest-info"
      v-if="
        user.roleLevel === 0 || user.roleLevel === 4 || user.roleLevel === 2
      "
      v-show="suggestShow"
    >
      <!--      <secondary-card title="城市建议（全重庆）" class="city-suggest">-->
      <!--        <div class="content-desc">-->
      <!--          <span class="num">{{ regionInfo.suggestCount }}</span-->
      <!--          ><span>条</span>-->
      <!--        </div>-->
      <!--      </secondary-card>-->
      <div class="region-info suggest">
        城市建议: <span>{{ regionInfo.suggestCount }}</span
        >条
      </div>
      <el-tabs
        class="center-tabs"
        v-model="activeSuggest"
        @tab-click="handleTabChange2"
      >
        <el-tab-pane label="分类型统计" name="type">
          <div class="rose-chart" ref="roseChartRef"></div>
        </el-tab-pane>
        <el-tab-pane
          label="分区县统计"
          name="region"
          v-if="user.roleLevel === 0 || user.roleLevel === 4"
        >
          <OrderPanel
            v-loading="rateGroupLoading"
            :datas="rateGroupData"
            color="#05D195"
            :hasIcon="true"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
.question-info {
  height: 100%;
  overflow-y: auto;

  .region-info {
    padding: 0 30px;
    font-size: 16px;
    color: #333;
    margin-bottom: 20px;

    span {
      color: #1890ff;
      font-size: 28px;
      font-weight: 700;
    }
  }

  .er-link {
    margin-left: 20px;
  }

  .suggest {
    width: calc(100% - 76px);
    padding-left: 0;
  }

  .rate-info {
    font-size: 16px;
    color: #333;
    margin-bottom: 20px;
    display: flex;
    padding-right: 20px;
    box-sizing: border-box;

    .total-question {
      width: 148px;
      height: 100px;
    }

    .center-card {
      display: flex;
      align-items: center;
      //width: 230px;
      height: 100px;
      box-shadow: rgba(0, 0, 0, 0.14) 0 6px 6px 0;
      margin-left: 16px;

      :deep(.secondary-card) {
        margin-left: 0;
        width: 115px;
        height: 100%;
        flex-shrink: 0;
        box-shadow: none;

        &:first-child {
          border-right: 1px solid #f0f0f0;
        }

        &:last-child {
          border-left: 1px solid #f0f0f0;
          width: 130px;
        }
      }
    }

    .rate-chart-content {
      flex: 1;
      margin-left: 18px;
      color: rgb(16, 16, 16);
      font-size: 12px;
      display: flex;
      flex-direction: column;

      .rate-chart-title {
        margin-bottom: 6px;
      }

      .rate-chart {
        flex: 1;
      }
    }

    :deep(.secondary-card) {
      margin-right: 0;
    }

    .content-desc {
      display: flex;
      align-items: center;
      padding-left: 20px;

      .num {
        font-size: 28px;
        color: #1890ff;
        margin-right: 6px;
      }
    }
  }

  .center-tabs {
    width: calc(100% - 40px);
    margin-left: 20px;
    margin-right: 20px;

    :deep(.order-panel-wrapper) {
      height: 400px;
      overflow-y: auto;
    }

    .rate-chart {
      width: 100%;
      height: 500px;

      div {
        width: 100% !important;
      }

      &.long-chart {
        height: 500px;
      }
    }
  }

  .total-chart {
    width: 100%;
    height: 800px;

    &.long-chart {
      height: 800px;
    }
  }

  .suggest-info {
    font-size: 16px;
    color: #333;
    display: flex;
    width: 100%;
    margin-top: 18px;
    flex-direction: column;
    align-items: center;

    .city-suggest {
      width: 174px;
      height: 125px;

      .content-desc {
        display: flex;
        align-items: center;
        padding-left: 20px;

        .num {
          font-size: 28px;
          color: #1890ff;
          margin-right: 6px;
        }
      }
    }

    .rose-chart {
      //width: 65%;
      height: 350px;
      margin-right: 20px;
    }
  }
}
</style>
